// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})
// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  })
  const db = cloud.database()
  const wxContext = cloud.getWXContext()

  app.router("getTip", async (ctx, next) => {
    const $ = db.command
    const res = await db.collection('list').where({
        is_delete: false,
        keywords: $.elemMatch(db.RegExp({
          regexp: event.keyword + '.*',
          options: 'i',
        }))
      })
      .get()
    ctx.body = {
      code: 200,
      data: res.data
    }
  })

  app.router("recode", async (ctx, next) => {
    const res = await db.collection('search').add({
      data: {
        _openid: wxContext.OPENID,
        date: new Date(),
        value: event.value
      }
    })
    ctx.body = {
      code: 200
    }

  })

  app.router("search", async (ctx, next) => {
    const $ = db.command
    let condition = {}
    if(event.keyword){
      condition.keywords = $.elemMatch(db.RegExp({
        regexp: event.keyword + '.*',
        options: 'i',
      }))
    }
    if(event.condition.type.length>0){
      condition.type = $.in(event.condition.type)
    }
    if(event.condition.tags.length>0){
      condition.tag = $.in(event.condition.tags)
    }
    if(event.condition.status.length>0){
      condition.status = $.in(event.condition.status)
    }
    if(event.condition.time.index !== null){
      condition.date = $.gte(new Date(event.condition.time.start)).and($.lte(new Date(event.condition.time.end)))
    }
    const res = await db.collection('list').where({
        is_delete: false,
        ...condition
      })
      .skip(event.skip)
      .limit(event.limit)
      .orderBy('date', 'desc')
      .get()
    
    ctx.body = {
      code: 200,
      data: res.data
    }
  })

  return app.serve()
}